import React from "react";
import { useLocation } from "react-router-dom";
import api from "src/http/api";
import { Layout } from "antd";
import EntityMysqlForm from "./mysql";
import PageLoading from "src/components/PageLoading";
import { getParams } from "src/utils";
import { EntityFormProps, IdcInfosProps } from "src/utils/interface";

const { useEffect, useState } = React;
const { Content } = Layout;

const EntityForm: React.FC = () => {
  const { storageUri, entityName } = getParams(useLocation().search);
  const [idc, setIdc] = useState([] as string[]);
  const [initValues, setInitValues] = useState({} as EntityFormProps);

  // 编辑 entity 时，需要从后端获取绑定的 storageUri
  const [storageUriValue, setStorageUriValue] = useState("");

  const getIdcs = (data: IdcInfosProps[]) => {
    let idcTemp: string[] = [];
    data?.forEach((item) => {
      idcTemp = idcTemp.concat(item.idc);
    });
    setIdc(idcTemp);
  };

  useEffect(() => {
    if (entityName) {
      api.getEntityByEntityName(entityName).then((res: any) => {
        getIdcs(res.data.storage?.idcInfos);
        setStorageUriValue(res.data.storage?.storageUri);
        setInitValues({ entity: res.data, mapping: res.data.mapping });
      });
    } else {
      api.getStorageByStorageUri(storageUri).then((res: any) => {
        console.log(res.data);
        getIdcs(res.data.idcInfos);
        setStorageUriValue(res.data.storageUri);
        setInitValues({ entity: res.data.entity, mapping: res.data.mapping });
      });
    }
  }, [entityName, storageUri]);

  if (!storageUriValue) return <PageLoading />;

  return (
    <Layout style={{ padding: "0 24px 24px" }}>
      <Content>
        <EntityMysqlForm
          storageUri={storageUriValue}
          idc={idc}
          initValues={initValues}
        />
      </Content>
    </Layout>
  );
};

export default EntityForm;
